import os
import pygeoip
import re
import matplotlib
import csv
from mapDisplay import loadMap
from pylab import *
from time import strptime
import collections
from reportlab.pdfgen import canvas

"""
Contains the main menu of the application
Manage the user inputs
"""

ipList = []
dateList = []
attacksByIPList = []
attacksByDateList = []

def startLogAnalyser():
	"""
	Method that shows the main menu of the Log Analyzer
	this methos also builds the csv file
	"""
	print ' '
	inputOption = raw_input('\n Load actual ufw.log? (y/n): ')

	if inputOption == 'y':
		os.system('cp /var/log/ufw.log .')
		print ' -> Copy ufw.log to current directory'

	os.system('cat ufw.log | sed "s:\[::g" | sed "s:]::g" | sed "s:SRC=::g" | sed "s:DST=::g" | tr -s " " | cut -d " " -f1,2,3,12,13 --output-delimiter="," > logs.csv')
	print ' -> File logs.csv builded'
	print ' '

	loadAllData()
	
	inputOption = 1

	while inputOption > 0:
		print ' 1 - List all attacks'
		print ' 2 - View attacks by country'
		print ' 3 - View attacks by date'
		print ' 4 - Create Report'
		print ' Something else - Back'
		
		try: inputOption = int(raw_input('\n Input selected option: '))
		except: inputOption = 0

                if inputOption == 1:
                        viewAllAttacks()
		elif inputOption == 2:
			numAttacksbyIP()
		elif inputOption == 3:
			numAttacksbyDate()
		elif inputOption == 4:
			createReport()
		else:
			break


def loadAllData():
	"""
	Method to be invoked at the beginning, to load into memory all the data necessary to the others methods
	"""
	inputFile = open('logs.csv', 'r')

	for row in csv.reader(open('logs.csv')):
		ipList.append(row[3]) 
		dateList.append(str(strptime(row[0], '%b').tm_mon) + '/' + row[1])

	inputFile.close()
	ipList.sort()


def viewAllAttacks():
	"""
	List all attacks captured
	"""
	print ' '
	print 'List All Attacks'
	inputFile = open('logs.csv', 'r')
	for row in csv.reader(open('logs.csv')):
		print row[3] + ' -> ' + row[2] + ' ' + row[1] + ' ' + row[0] 
	print ' '


def numAttacksbyIP():
	"""
	List the number os attacks by IP and Country
	"""
	print ' '
	print 'List number of attacks by IP'
	gi = pygeoip.GeoIP('GeoIP.dat', pygeoip.MEMORY_CACHE)
	IPCounter = dict()

	print ' '
	print 'Number of Attacks Detected: ' +  str(len(ipList))


	for x in ipList:
		if (re.search(":", x) or re.search("^0", x) or re.search("^192", x)):
			ipList.remove(x)
		else:
			if x in IPCounter: 
				IPCounter[x] += 1
			else:
				IPCounter[x] = 1

	print ' '

	keyList = IPCounter.keys()
	valueList = IPCounter.values()

	print("IP                      Country         Number of Attempts")



	for x in range(0, len(keyList)):
		if not re.search("192", keyList[x]):
			try:
				print keyList[x] + '\t===>\t' +  gi.country_code_by_addr(keyList[x]) + '\t===>\t' + str(valueList[x])
				attacksByIPList.append(keyList[x] + '   ===>   ' +  gi.country_code_by_addr(keyList[x]) + '   ===>   ' + str(valueList[x]))
			except:
				continue


	fig = plt.figure()
	fig.subplots_adjust(bottom=0.3)
	ax = fig.add_subplot(111)

	title('Attacks by IP')

	ax.bar(arange(len(valueList)), valueList)
	ax.ticklabel_format(style='plain')
	ax.set_xticks(arange(len(keyList)))
	ax.set_xticklabels(keyList, rotation=45)

	savefig('attacksByIP_Graph.png', dpi=100)

	print ' '
	print ' Graphic attacksByIP_Graph.png Created'
	print ' '


def numAttacksbyDate():
	"""
	Method that lists the percentage of atacks by date
	"""
	print ' '
	print 'List number of attacks by date'

	AttacksCounter = dict()
	print ' '
	total = len(ipList)
	print 'Number of Attacks Detected: ' + str(total)

	for x in dateList:
		if x in AttacksCounter: 
			AttacksCounter[x] += 1
		else:
			AttacksCounter[x] = 1

	print ' '

	od = collections.OrderedDict(sorted(AttacksCounter.items()))
	attacksList = od.keys()
	occList = od.values()

	print 'Date\t\tAttacks\t\tPercentage'
	
	for x in range(0, len(attacksList)):
		print attacksList[x] + '\t\t' + str(occList[x]) + '\t\t' + str(int(((float(occList[x])/total)*100))) + ' %'
		attacksByDateList.append(attacksList[x] + '     ' + str(occList[x]) + '     ' + str(int(((float(occList[x])/total)*100))) + ' %')
	

	fig = plt.figure()
	fig.subplots_adjust(bottom=0.3)
	ax = fig.add_subplot(111)
	title('Attacks by Date')
	ax.bar(arange(len(occList)), occList)
	ax.ticklabel_format(style='plain')
	ax.set_xticks(arange(len(attacksList)))
	ax.set_xticklabels(attacksList, rotation=0)
	savefig('attacksByDate_Graph.png', dpi=100)
	print ' '
	print ' Graphic attacksByDate_Graph.png Created'
	print ' '


def createReport():
	"""
	Method to create reports
	"""
	print ' '

	numAttacksbyIP()
	numAttacksbyDate()

	c = canvas.Canvas("logsReport.pdf")
	c.setAuthor("Luis Sobral - Carlos Marcelino")
	c.setTitle("Logs Report")

	c.setFillColorRGB(0.3, 0, 1)
	c.setFont("Helvetica", 24)
	c.drawString(20, 780, "Firewall Logs Report - From " + dateList[0] + " to " + dateList[len(dateList) - 1])

	c.setFillColorRGB(0.3, 0, 0.5)
	c.setFont("Helvetica", 20)
	c.drawString(20, 720, 'List of attacks by IP')

	c.setFillColorRGB(0, 0, 0)
	c.setFont("Helvetica", 12)

	downSpace = 0
	step = 15

	for x in range(0, len(attacksByIPList)):
		downSpace = (x * 15)
		c.drawString(20, (700 - downSpace), attacksByIPList.pop(0))


	c.setFillColorRGB(0.3, 0, 0.5)
	c.setFont("Helvetica", 20)

	c.drawString(300, 720, 'List of attacks by Date')

	downSpace = 0
	c.setFillColorRGB(0, 0, 0)
	c.setFont("Helvetica", 12)

	for x in range(0, len(attacksByDateList)):
		downSpace = (x * 15)
		c.drawString(300, (700 - downSpace), attacksByDateList.pop(0))

	c.drawImage('attacksByIP_Graph.png', 50, 300, 400, 300)	
	c.drawImage('attacksByDate_Graph.png', 50, 20, 400, 300)	

	c.showPage()
	c.save()
	print ' *** Report Done ***'
	print ' '

